<script>
import UserApi from "../../api/user"
import {mapStores} from "pinia"
import {useUserStore} from "../../stores/user"
import MyMessageBox from "../../components/MyMessageBox.vue";
export default {
    components: {MyMessageBox},
    data() {
        return {
            phoneNumber: "",
            password: "",
            msg: "",
            dangerText: {
                "text-danger": false
            }
        }
    },
    methods: {
        async login() {
            let data = { phoneNumber: this.phoneNumber, password: this.password };
            // console.log(data);
             try{
                let api = new UserApi();
                let res = await api.login(data);
                console.log(res);
                if (res.data.loginStatus === "failed") {
                    this.msg = `用户${this.username}登录失败！`;
                    this.dangerText["text-danger"] = true;
                } else {
                    this.msg = `用户${this.username}登录成功！`;
                    this.dangerText["text-danger"] = false;
                    //设置用户登录状态
                    this.userStore.isLogin = true;
                    this.userStore.userData = res.data;
                    this.$router.replace("/");
                }
            }catch(err){
                console.error(err);
               // this.$refs.myMsgBox.show("应用服务器访问错误");这种方法也可以，只是比较繁琐
                //下面是全局的方法,在main.js里面设置
                this.$myMessageBox("应用服务器访问错误");
            }
            
        }
    },
    computed: {
        ...mapStores(useUserStore)
    }
}
</script>

<template>
    <my-message-box ref="myMsgBox"/>
    <div class="login">
        <h2>用户登录</h2>
        <div>
            <label for="phoneNumber">账户</label>
            <input type="text" name="phoneNumber" id="phoneNumber" v-model="phoneNumber" placeholder="请输入电话号码">
        </div>
        <div>
            <label for="password">密码</label>
            <input type="password" name="password" id="password" v-model="password" placeholder="请输入密码">
        </div>
        <div>
            <button @click="login">登录</button>
        </div>
        <div>
            <p :class="dangerText">{{ msg }}</p>
        </div>
    </div>
</template>

<style scoped>
.login {
    margin: 50px auto;
    width: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.login div {
    margin-top: 1rem;
}

.login label {
    display: inline-block;
    width: 50px;
    padding: 0 10px;
    text-align-last: justify;
}

.text-danger {
    color: red;
}
</style>
